package com.flash.dataU.test.config;

import java.sql.SQLException;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

/**
 * H2 database setup.
 *
 * @author Flash (18811311416@sina.cn)
 * @since 2017-07-06 19:38
 */
@Component
public class DBConfig extends DataSourceInitializer {

    @Value("classpath:db.sql")
    private Resource schemaScript;

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void init() throws SQLException {
        setDataSource(dataSource);
        if (dataSource.getConnection().getCatalog().equals("H2DB")) {
            setDatabasePopulator(databasePopulator());
        }
    }

    private DatabasePopulator databasePopulator() {
        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(schemaScript);
        return populator;
    }
}
